/** @format */

import { getConfig } from '../../config/index'
import { sellerId } from '../../constants'
import { VIP_MOCK } from '../../vipMock'

import { TBAPIS } from '../../sdk'

/** @format */

// 测试环境 duib2账户mock数据  或者本地
export const isUseVipMock = (context: IContext<IParams>, activtiyInfo: IActivityInfo) => {
  const isTestEnv = context.env === 'test'
  const isMockEnv = context.env === 'mock'
  const isDuibaAccount = activtiyInfo?.activtiyInfoUserNick?.startsWith('duiba2')

  return (isTestEnv && isDuibaAccount) || isMockEnv
}

/**
 * @desc 获取是否是会员
 * @param {调用淘宝接口的session} session
 * @returns {isVip: boolean(是否是会员), url: string(入会链接) }
 */
export const getShopVip = async (
  context: IContext<any>,
  activityInfo: IActivityInfo,
  callbackUrl: string = ''
): Promise<IVipInfo> => {
  const shopUrl = generateVipUrl(callbackUrl)
  const { isVip = false } = context.data
 
  return {
    isVip,
    url: shopUrl
  }
}

// 生成会员链接
export const generateVipUrl = (callbackUrl: string) => {
  return `https://market.m.taobao.com/app/sj/member-center-rax/pages/pages_index_index?wh_weex=true&sellerId=${sellerId}&extraInfo=${encodeURIComponent(
    JSON.stringify({ source: 'isvapp', entrance: 'duiba' })
  )}&callbackUrl=${encodeURIComponent(callbackUrl)}`
}

// 格式化Vip回调地址
export const formatVipCbUrl = (context: IContext<IParams>) => {
  const { activityId, inviteId = '' } = context.data

  let { vipCallBackUrl } = getConfig(context)

  const handlerName = context?.cloud?.dataspace?.context?.handler

  // 拼接回调参数
  let query = `activityId=${activityId}`
  let pages = `pages/index/index?inviteId=${inviteId}&handlerName=${handlerName || ''}`

  let callbackUrl: string = `${vipCallBackUrl}&query=${encodeURIComponent(query)}&page=${encodeURIComponent(pages)}`
  return callbackUrl
}
